package com.salt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.salt.config.TaobaoConfig;
import com.salt.entity.IdleAffiliatePromotion;
import com.salt.entity.IdleAffiliateMaterial;
import com.salt.entity.User;
import com.salt.mapper.IdleAffiliatePromotionMapper;
import com.salt.mapper.IdleAffiliateMaterialMapper;
import com.salt.service.TaobaoApiService;
import com.salt.service.SystemConfigService;
import com.salt.utils.UserContext;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 淘宝API服务实现类
 */
@Slf4j
@Service
public class TaobaoApiServiceImpl implements TaobaoApiService {

    private TaobaoClient client;
    private String session;

    @Autowired
    private IdleAffiliatePromotionMapper promotionMapper;

    @Autowired
    private IdleAffiliateMaterialMapper materialMapper;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private TaobaoConfig taobaoConfig;

    @PostConstruct
    public void init() {
        String serverUrl = taobaoConfig.isUseHttps()
                ? "https://eco.taobao.com/router/rest"
                : "http://gw.api.taobao.com/router/rest";

        this.client = new DefaultTaobaoClient(
                serverUrl,
                taobaoConfig.getAppKey(),
                taobaoConfig.getAppSecret()
        );
        
        // 从系统配置中获取access token
        this.session = systemConfigService.getConfigValue("taobao_access_token");
        if (this.session == null) {
            log.error("淘宝access token未配置");
            throw new RuntimeException("淘宝access token未配置");
        }
    }

    // 最大重试次数
    private static final int MAX_RETRY_TIMES = 3;
    // 重试休眠时间(毫秒)
    private static final long RETRY_SLEEP_TIME = 3000;

    @Override
    public AlibabaIdleAffiliateMaterialGuideGetResponse getMaterialGuide() throws ApiException {
        log.info("开始获取物料指南");
        AlibabaIdleAffiliateMaterialGuideGetRequest req = new AlibabaIdleAffiliateMaterialGuideGetRequest();
        AlibabaIdleAffiliateMaterialGuideGetResponse response = client.execute(req, session);
        if (response.isSuccess()) {
            log.info("获取物料指南成功");
        } else {
            log.error("获取物料指南失败: {}", response.getSubMsg());
        }
        return response;
    }

    @Override
    public IdleAffiliatePromotion generatePromotionLink(String itemId, Long materialType) {
        try {
            log.info("开始生成推广链接，商品ID: {}", itemId);
            User user = UserContext.getUser();
            // 调用淘宝API生成推广链接
            AlibabaIdleAffiliateGeneralLinkConvertRequest req = new AlibabaIdleAffiliateGeneralLinkConvertRequest();
            AlibabaIdleAffiliateGeneralLinkConvertRequest.LinkConvertVO linkConvertVO = 
                new AlibabaIdleAffiliateGeneralLinkConvertRequest.LinkConvertVO();
            linkConvertVO.setMaterialType(materialType);
            if (materialType == 1L){
                linkConvertVO.setItemIds(Collections.singletonList(itemId));
            }else if (materialType == 4L){
                linkConvertVO.setXyUrl(Collections.singletonList(itemId));
            }else if (materialType == 5L){
                linkConvertVO.setActivityPageId(itemId);
            }
           if (user != null)
                linkConvertVO.setSubPublisherId(user.getInviteCode());
            req.setLinkConvertVo(linkConvertVO);
            req.setBatchApiSession(session);
            AlibabaIdleAffiliateGeneralLinkConvertResponse response = client.execute(req,session);
            
            if (response.isSuccess()) {
                log.info("生成推广链接成功");
                
                // 保存推广记录
                IdleAffiliatePromotion promotion = new IdleAffiliatePromotion();
                promotion.setMaterialType(materialType);
                if (materialType == 1L){
                    promotion.setItemId(itemId);
                }else if (materialType == 4L){
                    promotion.setXyUrl(itemId);
                }
                if (user != null)
                    promotion.setSubPublisherId(user.getInviteCode());
                promotion.setShortUrl(response.getResult().getResult().getShortUrl());
                promotion.setShortTpwd(response.getResult().getResult().getShortTpwd());
                promotion.setDeeplink(response.getResult().getResult().getDeeplink());
                promotion.setCreateTime(LocalDateTime.now());
                promotion.setUpdateTime(LocalDateTime.now());
                
                promotionMapper.insert(promotion);
                
                return promotion;
            } else {
                log.error("生成推广链接失败: {}", response.getSubMsg());
                throw new RuntimeException("生成推广链接失败: " + response.getSubMsg());
            }
        } catch (Exception e) {
            log.error("生成推广链接异常", e);
            throw new RuntimeException("生成推广链接异常", e);
        }
    }

    @Override
    public AlibabaIdleAffiliateMaterialQueryResponse queryMaterials(
        Long materialType,
        Long pageSize,
        Long pageNum,
        String tabName,
        String itemPublisherTime,
        String sellerCreditLevel,
        Boolean filterLevel5Yxp,
        Boolean filterYhb,
        String sellerName,
        String keyword
    ) throws ApiException {
            log.info("开始查询物料列表，类型: {}, 页码: {}, 每页数量: {}", materialType, pageNum, pageSize);

            log.info("开始查询闲鱼联盟物料，参数：materialType={}, pageSize={}, pageNum={}, keyword={}",
                    materialType, pageSize, pageNum, keyword);

            AlibabaIdleAffiliateMaterialQueryRequest req = new AlibabaIdleAffiliateMaterialQueryRequest();
            AlibabaIdleAffiliateMaterialQueryRequest.MaterialsQueryVO materialsQueryVO =
                    new AlibabaIdleAffiliateMaterialQueryRequest.MaterialsQueryVO();

            // 设置物料类型
            materialsQueryVO.setMaterialType(materialType);

            // 设置分页参数
            AlibabaIdleAffiliateMaterialQueryRequest.PageRequest pageRequest =
                    new AlibabaIdleAffiliateMaterialQueryRequest.PageRequest();
            pageRequest.setPageSize(pageSize);
            pageRequest.setPageNum(pageNum);
            materialsQueryVO.setPageRequest(pageRequest);

            // 设置商品导览参数
            AlibabaIdleAffiliateMaterialQueryRequest.ItemGuideVO itemGuideVO =
                    new AlibabaIdleAffiliateMaterialQueryRequest.ItemGuideVO();
            itemGuideVO.setTabName(tabName);
             itemGuideVO.setItemPublisherTime(itemPublisherTime);
             itemGuideVO.setSellerCreditLevel(sellerCreditLevel);
             itemGuideVO.setFilterLevel5Yxp(filterLevel5Yxp);
             itemGuideVO.setFilterYhb(filterYhb);
             itemGuideVO.setSellerName(sellerName);
            itemGuideVO.setKeyword(keyword);
            materialsQueryVO.setItemGuideVO(itemGuideVO);

            req.setMaterialsQueryVo(materialsQueryVO);

            AlibabaIdleAffiliateMaterialQueryResponse response = client.execute(req, session);
        if (response.isSuccess()) {
                log.info("查询物料列表成功");
                
                // 保存物料数据
                if (response.getResult() != null && response.getResult().getResult() != null) {
                    for (AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO : 
                        response.getResult().getResult()) {
                        
                        // 检查是否已存在
                        if (materialDTO != null && materialDTO.getItemInfo() != null 
                            && materialDTO.getItemInfo().getItemBaseInfo() != null 
                            && materialDTO.getItemInfo().getItemBaseInfo().getItemId() != null) {
                            
                            IdleAffiliateMaterial existingMaterial = materialMapper.selectOne(
                                new LambdaQueryWrapper<IdleAffiliateMaterial>()
                                    .eq(IdleAffiliateMaterial::getItemId, 
                                        materialDTO.getItemInfo().getItemBaseInfo().getItemId())
                            );
                            
                            if (existingMaterial != null) {
                                log.info("物料已存在，更新数据");
                                updateMaterial(existingMaterial, materialDTO);
                            } else {
                                log.info("物料不存在，新增数据");
                                saveMaterial(materialDTO);
                            }
                        } else {
                            log.warn("物料数据不完整，跳过处理");
                        }
                    }
                }
                
                return response;
            } else {
                log.error("查询物料列表失败: {}", response.getSubMsg());
               // throw new RuntimeException("查询物料列表失败: " + response.getSubMsg());
            }
         return null;
    }
    
    /**
     * 保存物料数据
     */
    private void saveMaterial(AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO) {
        if (materialDTO == null || materialDTO.getItemInfo() == null 
            || materialDTO.getItemInfo().getItemBaseInfo() == null) {
            log.warn("物料数据不完整，无法保存");
            return;
        }
        
        IdleAffiliateMaterial material = new IdleAffiliateMaterial();
        material.setMaterialType(materialDTO.getMaterialType());
        
        // 设置商品基本信息
        AlibabaIdleAffiliateMaterialQueryResponse.ItemBaseInfo baseInfo = 
            materialDTO.getItemInfo().getItemBaseInfo();
        material.setItemId(baseInfo.getItemId());
        material.setItemTitle(baseInfo.getItemTitle());
        material.setItemDesc(baseInfo.getItemDesc());
        material.setCategoryName(baseInfo.getCategoryName());
        material.setStatus(baseInfo.getStatus());
        material.setStatusDesc(baseInfo.getStatusDesc());
        
        // 添加空值判断
        if (StringUtils.isNotBlank(baseInfo.getReservePrice())) {
            material.setReservePrice(new BigDecimal(baseInfo.getReservePrice()));
        }
        if (StringUtils.isNotBlank(baseInfo.getOriginalPrice())) {
            material.setOriginalPrice(new BigDecimal(baseInfo.getOriginalPrice()));
        }
        
        material.setStuffStatus(baseInfo.getStuffStatus());
        material.setAuctionType(baseInfo.getAuctionType());
        material.setSkuItem(baseInfo.getSkuItem());
        material.setIsFishShop(baseInfo.getIsFishShop());
        material.setUserFishShopGrade(baseInfo.getUserFishShopGrade());
        material.setSellerLevelCode(baseInfo.getSellerLevelCode());
        material.setYhbItem(baseInfo.getYhbItem());
        material.setImageUrls(String.join(",", baseInfo.getImageUrls()));
        
        // 设置推广信息
        if (materialDTO.getItemInfo().getItemPromoteInfo() != null) {
            AlibabaIdleAffiliateMaterialQueryResponse.ItemPromoteInfo promoteInfo = 
                materialDTO.getItemInfo().getItemPromoteInfo();
            if (StringUtils.isNotBlank(promoteInfo.getCommissionRate())) {
                material.setCommissionRate(new BigDecimal(promoteInfo.getCommissionRate()));
            }
            if (StringUtils.isNotBlank(promoteInfo.getEstimatedCommission())) {
                material.setEstimatedCommission(new BigDecimal(promoteInfo.getEstimatedCommission()));
            }
        }
        
        // 设置优惠券信息
        if (materialDTO.getCouponInfo() != null) {
            material.setCouponId(materialDTO.getCouponInfo().getCouponId());
            material.setCouponName(materialDTO.getCouponInfo().getCouponName());
        }
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        material.setCreateTime(now);
        material.setUpdateTime(now);
        
        materialMapper.insert(material);
    }
    
    /**
     * 更新物料数据
     */
    private void updateMaterial(IdleAffiliateMaterial existingMaterial, 
        AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO) {
        
        if (!systemConfigService.getBooleanConfig("allow_material_update", true)) {
            log.info("物料更新功能已禁用，跳过更新");
            return;
        }
        
        if (materialDTO == null || materialDTO.getItemInfo() == null 
            || materialDTO.getItemInfo().getItemBaseInfo() == null) {
            log.warn("物料数据不完整，无法更新");
            return;
        }
        
        // 更新商品基本信息
        AlibabaIdleAffiliateMaterialQueryResponse.ItemBaseInfo baseInfo = 
            materialDTO.getItemInfo().getItemBaseInfo();
        existingMaterial.setItemTitle(baseInfo.getItemTitle());
        existingMaterial.setItemDesc(baseInfo.getItemDesc());
        existingMaterial.setCategoryName(baseInfo.getCategoryName());
        existingMaterial.setStatus(baseInfo.getStatus());
        existingMaterial.setStatusDesc(baseInfo.getStatusDesc());
        
        // 添加空值判断
        if (StringUtils.isNotBlank(baseInfo.getReservePrice())) {
            existingMaterial.setReservePrice(new BigDecimal(baseInfo.getReservePrice()));
        }
        if (StringUtils.isNotBlank(baseInfo.getOriginalPrice())) {
            existingMaterial.setOriginalPrice(new BigDecimal(baseInfo.getOriginalPrice()));
        }
        
        existingMaterial.setStuffStatus(baseInfo.getStuffStatus());
        existingMaterial.setAuctionType(baseInfo.getAuctionType());
        existingMaterial.setSkuItem(baseInfo.getSkuItem());
        existingMaterial.setIsFishShop(baseInfo.getIsFishShop());
        existingMaterial.setUserFishShopGrade(baseInfo.getUserFishShopGrade());
        existingMaterial.setSellerLevelCode(baseInfo.getSellerLevelCode());
        existingMaterial.setYhbItem(baseInfo.getYhbItem());
        existingMaterial.setImageUrls(String.join(",", baseInfo.getImageUrls()));
        
        // 更新推广信息
        if (materialDTO.getItemInfo().getItemPromoteInfo() != null) {
            AlibabaIdleAffiliateMaterialQueryResponse.ItemPromoteInfo promoteInfo = 
                materialDTO.getItemInfo().getItemPromoteInfo();
            if (StringUtils.isNotBlank(promoteInfo.getCommissionRate())) {
                existingMaterial.setCommissionRate(new BigDecimal(promoteInfo.getCommissionRate()));
            }
            if (StringUtils.isNotBlank(promoteInfo.getEstimatedCommission())) {
                existingMaterial.setEstimatedCommission(new BigDecimal(promoteInfo.getEstimatedCommission()));
            }
        }
        
        // 更新优惠券信息
        if (materialDTO.getCouponInfo() != null) {
            existingMaterial.setCouponId(materialDTO.getCouponInfo().getCouponId());
            existingMaterial.setCouponName(materialDTO.getCouponInfo().getCouponName());
        }
        
        // 更新时间
        existingMaterial.setUpdateTime(LocalDateTime.now());
        
        materialMapper.updateById(existingMaterial);
    }

    @Override
    public AlibabaIdleAffiliateIncomeSummaryResponse getIncomeSummary() throws ApiException {
        log.info("开始获取收入汇总");
        AlibabaIdleAffiliateIncomeSummaryRequest req = new AlibabaIdleAffiliateIncomeSummaryRequest();
        AlibabaIdleAffiliateIncomeSummaryResponse response = client.execute(req, session);
        if (response.isSuccess()) {
            log.info("获取收入汇总成功");
            if (response.getResult() != null && response.getResult().getResult() != null) {
                log.info("累计收入: {}, 未结算收入: {}, 账户余额: {}", 
                    response.getResult().getResult().getAccumulatedAmountText(),
                    response.getResult().getResult().getUnaccountedAmountText(),
                    response.getResult().getResult().getBalanceText());
            }
            return response;
        } else {
            log.error("获取收入汇总失败: {}", response.getSubMsg());
            throw new RuntimeException("获取收入汇总失败: " + response.getSubMsg());
        }
    }

    public AlibabaIdleAffiliateCpsIncomeDetailsSignleQueryResponse queryCpsIncomeDetailsResponse(
            List<String> plainBillId
    ) throws ApiException {
       List<String> id = new ArrayList<>();
        id.add("JNtTN9pXglccHgOERfOSZJtX2p+fGdfmggQp/h2DlJc=");
        id.add("8eLHKghB0B3pzm2TtcB1gZtX2p+fGdfmggQp/h2DlJc=");
        AlibabaIdleAffiliateCpsIncomeDetailsSignleQueryRequest req = new AlibabaIdleAffiliateCpsIncomeDetailsSignleQueryRequest();
        AlibabaIdleAffiliateCpsIncomeDetailsSignleQueryRequest.IncomeDetailVO obj1 = new AlibabaIdleAffiliateCpsIncomeDetailsSignleQueryRequest.IncomeDetailVO();
       // obj1.setPlainBillIdList(id);
        obj1.setPlainBillId("8eLHKghB0B3pzm2TtcB1gZtX2p+fGdfmggQp/h2DlJc=");
        req.setIncomeDetailVo(obj1);
        AlibabaIdleAffiliateCpsIncomeDetailsSignleQueryResponse rsp = client.execute(req, session);
        System.out.println(rsp.getBody());
        return rsp;
    }
    
    @Override
    public AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse queryCpsIncomeDetails(
        String createMonth,
        Long billState,
        Long pageSize,
        Long pageNum,
        Long startCreateTimeStamp,
        Long endCreateTimeStamp,
        Long startUpdateTime,
        Long endUpdateTime
    ) throws ApiException {
        log.info("开始查询CPS佣金明细，创建月份: {}, 账单状态: {}, 页码: {}, 每页数量: {}", 
            createMonth, billState, pageNum, pageSize);
        
        AlibabaIdleAffiliateCpsIncomeDetailsQueryRequest req = new AlibabaIdleAffiliateCpsIncomeDetailsQueryRequest();
        
        // 设置查询条件
        AlibabaIdleAffiliateCpsIncomeDetailsQueryRequest.IncomeDetailVO incomeDetailVO = 
            new AlibabaIdleAffiliateCpsIncomeDetailsQueryRequest.IncomeDetailVO();
        incomeDetailVO.setCreateMonth(createMonth);
        incomeDetailVO.setBillState(billState);
        
        // 设置分页参数
        AlibabaIdleAffiliateCpsIncomeDetailsQueryRequest.PageRequest pageRequest = 
            new AlibabaIdleAffiliateCpsIncomeDetailsQueryRequest.PageRequest();
        pageRequest.setPageSize(pageSize);
        pageRequest.setPageNum(pageNum);
        incomeDetailVO.setPageRequest(pageRequest);
        
        // 设置时间范围
        incomeDetailVO.setStartCreateTimeStamp(startCreateTimeStamp);
        incomeDetailVO.setEndCreateTimeStamp(endCreateTimeStamp);
        incomeDetailVO.setStartUpdateTime(startUpdateTime);
        incomeDetailVO.setEndUpdateTime(endUpdateTime);
        
        req.setIncomeDetailVo(incomeDetailVO);
        
        // 重试机制
        int retryCount = 0;
        while (true) {
            try {
                AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse response = client.execute(req, session);
                if (response.isSuccess()) {
                    log.info("查询CPS佣金明细成功");
                    return response;
                }
                
                // 检查是否是限流错误
                if (isFlowLimitError(response)) {
                    retryCount++;
                    if (retryCount >= MAX_RETRY_TIMES) {
                        log.error("查询CPS佣金明细失败，已达到最大重试次数: {}", retryCount);
                        return response;
                    }
                    
                    log.warn("查询CPS佣金明细遇到限流，第{}次重试，休眠{}秒", retryCount, RETRY_SLEEP_TIME / 1000);
                    TimeUnit.MILLISECONDS.sleep(RETRY_SLEEP_TIME);
                    continue;
                }
                
                log.error("查询CPS佣金明细失败: {}", response.getSubMsg());
                return response;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new ApiException("查询CPS佣金明细被中断", e);
            }
        }
    }
    
    /**
     * 检查是否是限流错误
     */
    private boolean isFlowLimitError(AlibabaIdleAffiliateCpsIncomeDetailsQueryResponse response) {
        return response.getErrorCode() != null 
            && response.getErrorCode().equals("15")
            && response.getSubCode() != null 
            && response.getSubCode().equals("AFFILIATE_FLOW_LIMIT_ERROR");
    }

    @Override
    public AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse queryCpaIncomeDetails(
        Long billState,
        Long pageSize,
        Long pageNum,
        Long startTime,
        Long endTime
    ) throws ApiException {
        log.info("开始查询CPA佣金明细，账单状态: {}, 页码: {}, 每页数量: {}", 
            billState, pageNum, pageSize);
        
        AlibabaIdleAffiliateCpaIncomeDetailsQueryRequest req = new AlibabaIdleAffiliateCpaIncomeDetailsQueryRequest();
        
        // 设置查询条件
        AlibabaIdleAffiliateCpaIncomeDetailsQueryRequest.CpaBillQueryParams cpaBillQueryParams = 
            new AlibabaIdleAffiliateCpaIncomeDetailsQueryRequest.CpaBillQueryParams();
        cpaBillQueryParams.setBillState(billState);
        
        // 设置分页参数
        AlibabaIdleAffiliateCpaIncomeDetailsQueryRequest.PageRequest pageRequest = 
            new AlibabaIdleAffiliateCpaIncomeDetailsQueryRequest.PageRequest();
        pageRequest.setPageSize(pageSize);
        pageRequest.setPageNum(pageNum);
        cpaBillQueryParams.setPageRequest(pageRequest);
        
        // 设置时间范围
        cpaBillQueryParams.setStartTime(startTime);
        cpaBillQueryParams.setEndTime(endTime);
        
        req.setCpaBillQueryParams(cpaBillQueryParams);
        
        AlibabaIdleAffiliateCpaIncomeDetailsQueryResponse response = client.execute(req, session);
        if (response.isSuccess()) {
            log.info("查询CPA佣金明细成功");
        } else {
            log.error("查询CPA佣金明细失败: {}", response.getSubMsg());
        }
        return response;
    }

    @Override
    public AlibabaIdleAffiliateCpaIncomeSummaryResponse getCpaIncomeSummary() throws ApiException {
        log.info("开始获取CPA收入汇总");
        AlibabaIdleAffiliateCpaIncomeSummaryRequest req = new AlibabaIdleAffiliateCpaIncomeSummaryRequest();
        AlibabaIdleAffiliateCpaIncomeSummaryResponse response = client.execute(req, session);
        if (response.isSuccess()) {
            log.info("获取CPA收入汇总成功");
            if (response.getResult() != null && response.getResult().getResult() != null) {
                log.info("累计收入: {}, 未结算收入: {}, 账户余额: {}", 
                    response.getResult().getResult().getAccumulatedAmountText(),
                    response.getResult().getResult().getUnaccountedAmountText(),
                    response.getResult().getResult().getBalanceText());
            }
            return response;
        } else {
            log.error("获取CPA收入汇总失败: {}", response.getSubMsg());
            throw new RuntimeException("获取CPA收入汇总失败: " + response.getSubMsg());
        }
    }

    @Override
    public AlibabaIdleAffiliateMaterialExactGetResponse getAndSaveMaterial(String itemId) throws Exception {
            // 创建请求对象
        AlibabaIdleAffiliateMaterialExactGetRequest req = new AlibabaIdleAffiliateMaterialExactGetRequest();
        AlibabaIdleAffiliateMaterialExactGetRequest.MaterialsExactQueryVO queryVO = new AlibabaIdleAffiliateMaterialExactGetRequest.MaterialsExactQueryVO();
        queryVO.setMaterialType(1L);
        queryVO.setItemIds(Collections.singletonList(itemId));
        req.setMaterialsExactQueryVo(queryVO);

            // 执行请求
            AlibabaIdleAffiliateMaterialExactGetResponse response = client.execute(req, session);

            if (response.isSuccess()) {
                log.info("查询物料列表成功");

                // 保存物料数据
                if (response.getResult() != null && response.getResult().getResult() != null) {
                    for (AlibabaIdleAffiliateMaterialExactGetResponse.MaterialDTO materialDTO :
                            response.getResult().getResult()) {

                        // 检查是否已存在
                        if (materialDTO != null && materialDTO.getItemInfo() != null
                                && materialDTO.getItemInfo().getItemBaseInfo() != null
                                && materialDTO.getItemInfo().getItemBaseInfo().getItemId() != null) {

                            IdleAffiliateMaterial existingMaterial = materialMapper.selectOne(
                                    new LambdaQueryWrapper<IdleAffiliateMaterial>()
                                            .eq(IdleAffiliateMaterial::getItemId,
                                                    materialDTO.getItemInfo().getItemBaseInfo().getItemId())
                            );

                            if (existingMaterial != null) {
                                log.info("物料已存在，更新数据");
                                updateMaterials(existingMaterial, materialDTO);
                            } else {
                                log.info("物料不存在，新增数据");
                                saveMaterials(materialDTO);
                            }
                        } else {
                            log.warn("物料数据不完整，跳过处理");
                        }
                    }
                }

                return response;
            } else {
                log.error("查询物料列表失败: {}", response.getSubMsg());
                // throw new RuntimeException("查询物料列表失败: " + response.getSubMsg());
            }
        return null;
    }

    private void saveMaterials(AlibabaIdleAffiliateMaterialExactGetResponse.MaterialDTO materialDTO) {
        if (materialDTO == null || materialDTO.getItemInfo() == null
                || materialDTO.getItemInfo().getItemBaseInfo() == null) {
            log.warn("物料数据不完整，无法保存");
            return;
        }

        IdleAffiliateMaterial material = new IdleAffiliateMaterial();
        material.setMaterialType(materialDTO.getMaterialType());

        // 设置商品基本信息
        AlibabaIdleAffiliateMaterialExactGetResponse.ItemBaseInfo baseInfo =
                materialDTO.getItemInfo().getItemBaseInfo();
        material.setItemId(baseInfo.getItemId());
        material.setItemTitle(baseInfo.getItemTitle());
        material.setItemDesc(baseInfo.getItemDesc());
        material.setCategoryName(baseInfo.getCategoryName());
        material.setStatus(baseInfo.getStatus());
        material.setStatusDesc(baseInfo.getStatusDesc());

        // 添加空值判断
        if (StringUtils.isNotBlank(baseInfo.getReservePrice())) {
            material.setReservePrice(new BigDecimal(baseInfo.getReservePrice()));
        }
        if (StringUtils.isNotBlank(baseInfo.getOriginalPrice())) {
            material.setOriginalPrice(new BigDecimal(baseInfo.getOriginalPrice()));
        }

        material.setStuffStatus(baseInfo.getStuffStatus());
        material.setAuctionType(baseInfo.getAuctionType());
       // material.setSkuItem(baseInfo.getSkuItem());
        material.setIsFishShop(baseInfo.getIsFishShop());
        material.setUserFishShopGrade(baseInfo.getUserFishShopGrade());
        material.setSellerLevelCode(baseInfo.getSellerLevelCode());
        material.setYhbItem(baseInfo.getYhbItem());
        material.setImageUrls(String.join(",", baseInfo.getImageUrls()));

        // 设置推广信息
        if (materialDTO.getItemInfo().getItemPromoteInfo() != null) {
            AlibabaIdleAffiliateMaterialExactGetResponse.ItemPromoteInfo promoteInfo =
                    materialDTO.getItemInfo().getItemPromoteInfo();
            if (StringUtils.isNotBlank(promoteInfo.getCommissionRate())) {
                material.setCommissionRate(new BigDecimal(promoteInfo.getCommissionRate()));
            }
            if (StringUtils.isNotBlank(promoteInfo.getEstimatedCommission())) {
                material.setEstimatedCommission(new BigDecimal(promoteInfo.getEstimatedCommission()));
            }
        }

        // 设置优惠券信息
        if (materialDTO.getCouponInfo() != null) {
            material.setCouponId(materialDTO.getCouponInfo().getCouponId());
            material.setCouponName(materialDTO.getCouponInfo().getCouponName());
        }

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        material.setCreateTime(now);
        material.setUpdateTime(now);

        materialMapper.insert(material);
    }

    /**
     * 更新物料数据
     */
    private void updateMaterials(IdleAffiliateMaterial existingMaterial,
                                 AlibabaIdleAffiliateMaterialExactGetResponse.MaterialDTO materialDTO) {

        if (!systemConfigService.getBooleanConfig("allow_material_update", true)) {
            log.info("物料更新功能已禁用，跳过更新");
            return;
        }

        if (materialDTO == null || materialDTO.getItemInfo() == null
                || materialDTO.getItemInfo().getItemBaseInfo() == null) {
            log.warn("物料数据不完整，无法更新");
            return;
        }

        // 更新商品基本信息
        AlibabaIdleAffiliateMaterialExactGetResponse.ItemBaseInfo baseInfo =
                materialDTO.getItemInfo().getItemBaseInfo();
        existingMaterial.setItemTitle(baseInfo.getItemTitle());
        existingMaterial.setItemDesc(baseInfo.getItemDesc());
        existingMaterial.setCategoryName(baseInfo.getCategoryName());
        existingMaterial.setStatus(baseInfo.getStatus());
        existingMaterial.setStatusDesc(baseInfo.getStatusDesc());

        // 添加空值判断
        if (StringUtils.isNotBlank(baseInfo.getReservePrice())) {
            existingMaterial.setReservePrice(new BigDecimal(baseInfo.getReservePrice()));
        }
        if (StringUtils.isNotBlank(baseInfo.getOriginalPrice())) {
            existingMaterial.setOriginalPrice(new BigDecimal(baseInfo.getOriginalPrice()));
        }

        existingMaterial.setStuffStatus(baseInfo.getStuffStatus());
        existingMaterial.setAuctionType(baseInfo.getAuctionType());
       // existingMaterial.setSkuItem(baseInfo.getSkuItem());
        existingMaterial.setIsFishShop(baseInfo.getIsFishShop());
        existingMaterial.setUserFishShopGrade(baseInfo.getUserFishShopGrade());
        existingMaterial.setSellerLevelCode(baseInfo.getSellerLevelCode());
        existingMaterial.setYhbItem(baseInfo.getYhbItem());
        existingMaterial.setImageUrls(String.join(",", baseInfo.getImageUrls()));

        // 更新推广信息
        if (materialDTO.getItemInfo().getItemPromoteInfo() != null) {
            AlibabaIdleAffiliateMaterialExactGetResponse.ItemPromoteInfo promoteInfo =
                    materialDTO.getItemInfo().getItemPromoteInfo();
            if (StringUtils.isNotBlank(promoteInfo.getCommissionRate())) {
                existingMaterial.setCommissionRate(new BigDecimal(promoteInfo.getCommissionRate()));
            }
            if (StringUtils.isNotBlank(promoteInfo.getEstimatedCommission())) {
                existingMaterial.setEstimatedCommission(new BigDecimal(promoteInfo.getEstimatedCommission()));
            }
        }

        // 更新优惠券信息
        if (materialDTO.getCouponInfo() != null) {
            existingMaterial.setCouponId(materialDTO.getCouponInfo().getCouponId());
            existingMaterial.setCouponName(materialDTO.getCouponInfo().getCouponName());
        }

        // 更新时间
        existingMaterial.setUpdateTime(LocalDateTime.now());

        materialMapper.updateById(existingMaterial);
    }


}